<?php
/* SVN FILE: $Id: skinImportExport.php 231 2009-09-28 17:24:43Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Install Plugins
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 231 $
* @lastrevision $Date: 2009-09-28 17:24:43 +0000 (Mon, 28 Sep 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-09-28 17:24:43 +0000 (Mon, 28 Sep 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/sources/plugin/skinImportExport.php $
*/


if ( ! defined( 'IN_IPB' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit();
}

class skinImportExport extends skinCaching
{
	/**#@+
	 * Registry objects
	 *
	 * @access	protected
	 * @var		object
	 */	
	protected $registry;
	protected $DB;
	protected $settings;
	protected $request;
	protected $lang;
	protected $member;
	protected $cache;
	/**#@-*/
	
	/**
	 * Constructor
	 *
	 * @access	public
	 * @param	object		Registry object
	 * @return	void
	 */
	public function __construct( ipsRegistry $registry )
	{
		/* Make object */
		parent::__construct( $registry );
	}
	
	/**
	 * Imports a replacements XMLArchive
	 *
	 * @access	public
	 * @param	string		XMLArchive content to import
	 * @param	int			Set ID to apply to (if desired)
	 * @return	int			Number of items added
	 */
	public function importReplacementsXMLArchive( $content, $setID=0 )
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$addedCount  = 0;
		
		//-----------------------------------------
		// Got anything?
		//-----------------------------------------
		
		$replacements = $this->parseReplacementsXML( $content );
		
		//-----------------------------------------
		// Replacements...
		//-----------------------------------------
		
		if ( is_array( $replacements ) )
		{
			$this->DB->delete( 'skin_replacements', 'replacement_set_id=' . $setID );
			
			foreach( $replacements as $replacement )
			{
				if ( $replacement['replacement_key'] )
				{
					$addedCount++;
					
					$this->DB->insert( 'skin_replacements', array( 'replacement_key'      => $replacement['replacement_key'],
																   'replacement_content'  => $replacement['replacement_content'],
																   'replacement_set_id'   => $setID,
																   'replacement_added_to' => $setID ) );
				}
			}
		}
		
		$this->rebuildReplacementsCache( $setID );
		$this->rebuildSkinSetsCache( $setID );
		
		return $addedCount;
	}
	
	/**
	 * Import CSS for a single app
	 *
	 * @access	public
	 * @param	string		App
	 * @param	string		Skin key to import
	 * @param	int			Set ID
	 * @return	mixed		bool, or number of items added
	 */
	public function importCSSAppXML( $plugin, $skinKey, $setID=0 )
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$fileXML        = IPSLib::getAppDir('ibmarket')."/plugins/".$plugin."/xml/" . $skinKey . '_css.xml';
		$return			= array( 'updateCount' => 0, 'insertCount' => 0, 'updateBits' => array(), 'insertBits' => array() );
		
		//-----------------------------------------
		// File exists
		//-----------------------------------------
		
		if ( ! file_exists( $fileXML ) )
		{
			return FALSE;
		}
		
		if ( ! $setID and $skinKey != 'root' )
		{
			/* Figure out correct set ID based on key */
			$skinSetData = $this->DB->buildAndFetch( array( 'select' => '*',
															'from'   => 'skin_collections',
															'where'  => "set_key='" . $skinKey . "'" ) );
															
			$setID = $skinSetData['set_id'];
		}
		
		//-----------------------------------------
		// Fetch CSS
		//-----------------------------------------
		
		$css = $this->parseCSSXML( file_get_contents( $fileXML ) );
		
		if ( is_array( $css ) )
		{
			foreach( $css as $_css )
			{
				if ( $_css['css_group'] )
				{
					$return['insertCount']++;
					
					if ( $setID )
					{
						$this->DB->delete( 'skin_css', 'css_set_id=' . $setID . ' AND css_group=\'' . addslashes( $_css['css_group'] ) . '\' AND css_app=\'' . addslashes( $_css['css_app'] ) . '\'' );
					}
					
					$this->DB->insert( 'skin_css', array( 'css_group'       => $_css['css_group'],
														  'css_content'     => $_css['css_content'],
														  'css_position'    => $_css['css_position'],
														  'css_updated'     => time(),
														  'css_app'		    => $_css['css_app'],
														  'css_app_hide'    => $_css['css_app_hide'],
														  'css_attributes'  => $_css['css_attributes'],
														  'css_modules'		=> $_css['css_modules'],
														  'css_set_id'      => $setID,
														  'css_added_to'    => $setID ) );
				}
			}
		}

		return $return;
	}
	
	/**
	 * Import a single plugin
	 *
	 * @access	public
	 * @param	string		Plugin
	 * @param	string		Skin key to import
	 * @param	int			Set ID
	 * @param	boolean		Set the edited / added flags to 0 (from install, upgrade)
	 * @return	mixed		bool, or array of info
	 */
	public function importTemplatePluginXML( $plugin, $skinKey, $setID=0, $ignoreAddedEditedFlag=false )
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$templateGroups = array();
		$templates      = array();
		$fileXML        = IPSLib::getAppDir('ibmarket')."/plugins/".$plugin."/xml/" . $skinKey . '_templates.xml';
		$infoXML        = IPSLib::getAppDir('ibmarket')."/plugins/".$this->request['plugin']."/xml/information.xml";
		$return			= array( 'updateCount' => 0, 'insertCount' => 0, 'updateBits' => array(), 'insertBits' => array() );
		
		if( ! file_exists($fileXML) )
		{
			return $return;
		}
		
		if ( ! $setID and $skinKey != 'root' )
		{
			/* Figure out correct set ID based on key */
			$skinSetData = $this->DB->buildAndFetch( array( 'select' => '*',
															'from'   => 'skin_collections',
															'where'  => "set_key='" . $skinKey . "'" ) );
															
			$setID = $skinSetData['set_id'];
		}
		
		/* Set ignore flag correctly */
		if ( ! empty( $skinKey ) AND in_array( $skinKey, array( 'root', 'lofi', 'xmlskin' ) ) )
		{
			$ignoreAddedEditedFlag = true;
		}
		
		//-----------------------------------------
		// XML
		//-----------------------------------------
		
		require_once( IPS_KERNEL_PATH.'classXML.php' );
		$xml = new classXML( IPS_DOC_CHAR_SET );
		
		//-----------------------------------------
		// Get information file
		//-----------------------------------------
		
		$xml->load( $infoXML );
		
		foreach( $xml->fetchElements( 'template' ) as $template )
		{
			$name  = $xml->fetchItem( $template );
			$match = $xml->fetchAttribute( $template, 'match' );
		
			if ( $name )
			{
				$templateGroups[ $name ] = $match;
			}
		}
		
		if ( ! is_array( $templateGroups ) OR ! count( $templateGroups ) )
		{
			$this->_addMessage( "Nothing to export for " . $plugin );
			return FALSE;
		}
		
		//-----------------------------------------
		// Fetch templates
		//-----------------------------------------
		
		$_templates = $this->fetchTemplates( $setID, 'allNoContent' );
		$_MASTER    = $this->fetchTemplates( 0, 'allNoContent' );
		
		//-----------------------------------------
		// Loop through...
		//-----------------------------------------
		
		foreach( $_templates as $group => $data )
		{
			$_okToGo = FALSE;
			
			foreach( $templateGroups as $name => $match )
			{
				if ( $match == 'contains' )
				{
					if ( stristr( $group, $name ) )
					{
						$_okToGo = TRUE;
						break;
					}
				}
				else if ( $group == $name )
				{
					$_okToGo = TRUE;
				}
			}
			
			if ( $_okToGo === TRUE )
			{
				foreach( $data as $name => $templateData )
				{
					$templates[ $group ][ $name ] = $templateData;
				}
			}
		}
		
		//-----------------------------------------
		// Wipe the master skins
		//-----------------------------------------
		
		if ( $setID == 0 )
		{
			$this->DB->delete( 'skin_templates', "template_set_id=0 AND template_group IN ('" . implode( "','", array_keys( $templates ) ) . "') AND template_user_added=0 AND template_added_to=0" );
			
			/* Now wipe the array so we enforce creation */
			unset( $templates );
		}
		
		//-----------------------------------------
		// Now grab the actual XML files
		//-----------------------------------------
		
		$xml->load( $fileXML );
		
		foreach( $xml->fetchElements( 'template' ) as $templatexml )
		{
			$data = $xml->fetchElementsFromRecord( $templatexml );
			
			/* Figure out if this is added by a user or not */
			if ( $ignoreAddedEditedFlag === TRUE )
			{
				$isAdded  = 0;
				$isEdited = 0;
			}
			else
			{
				$isAdded  = ( is_array( $_MASTER[ $data['template_group'] ][ strtolower( $data['template_name'] ) ] ) AND ! $_MASTER[ $data['template_group'] ][ strtolower( $data['template_name'] ) ]['template_user_added'] ) ? 0 : 1;
				$isEdited = 1;
			}
			
			if ( is_array( $templates[ $data['template_group'] ][ strtolower( $data['template_name'] ) ] ) AND $templates[ $data['template_group'] ][ strtolower( $data['template_name'] ) ]['template_set_id'] == $setID )
			{
				/* Update.. */
				$return['updateCount']++;
				$return['updateBits'][] = $data['template_name'];
				$this->DB->update( 'skin_templates', array( 'template_content'     => $data['template_content'],
															'template_data'        => $data['template_data'],
															'template_user_edited' => $isEdited,
														    'template_user_added'  => $isAdded,
															'template_updated'     => time() ), 'template_set_id=' . $setID . " AND template_group='" . $data['template_group'] . "' AND template_name='" . $data['template_name'] . "'" );
			}
			else
			{
				/* Add... */
				$return['insertCount']++;
				$return['insertBits'][] = $data['template_name'];
				$this->DB->insert( 'skin_templates', array( 'template_set_id'      => $setID,
															'template_group'       => $data['template_group'],
														    'template_content'     => $data['template_content'],
														    'template_name'        => $data['template_name'],
														    'template_data'        => $data['template_data'],
														    'template_removable'   => ( $setID ) ? $data['template_removable'] : 0,
														    'template_added_to'    => $setID,
														    'template_user_edited' => $isEdited,
														    'template_user_added'  => $isAdded,
														    'template_updated'     => time() ) );
			}
		}
		
		return $return;
	}
}